var oper = getQueryString('oper')
var pktId = null

//全局js值保存。
var menuCopyType; //ztree复制节点的页面类型
var menuCopyNodes; //ztree复制节点临时存储

var queryPktListTreeUrl = "/comm/syscommpkt/createTree";


var baseUrl = '/pages/pre/msg/type/'
var typeConfig = {
  'policy': {
    url: baseUrl + 'policyEdit',
    label: '报文',
    type: {
      "fixed": '定长报文',
      "delim": '分隔符报文',
      "xml": 'XML报文',
      "cnaps1": 'CNAPS1报文',
      "cnaps2": 'CNAPS2报文',
      "http": 'HTTP报文',
      "json": 'JSON报文',
      "iso8583": 'ISO8583报文',
    }
  },
  'field': {
    url: baseUrl + 'fieldEdit',
    label: '报文字段'
  },
  'loop': {
    url: baseUrl + 'loopEdit',
    label: '报文循环'
  },
  'struct': {
    url: baseUrl + 'structEdit',
    label: '报文域'
  },
  'switch': {
    url: baseUrl + 'switchEdit',
    label: '报文分支'
  },
  'default': {
    url: baseUrl + 'defaultEdit',
    label: '分支默认条件'
  },
  'case': {
    url: baseUrl + 'caseEdit',
    label: '报文分支节点'
  },
}

var saveCfg = api + "/comm/syscommpkt";
var pktSelectNode;
var zTree;
var treeNode;
var rMenu;
var nodeTid;


var addList = {
  more: [
    {
      label: '报文',
      value: 'policy',
      addType: 'more'
    },
    {
      label: '报文字段',
      value: 'field',
      addType: 'single'
    },
    {
      label: '报文循环',
      value: 'loop',
      addType: 'more'
    },
    {
      label: '报文域',
      value: 'struct',
      addType: 'more'
    },
    {
      label: '报文分支',
      value: 'switch',
      addType: 'more',
      child: [
        {
          label: '分支默认条件',
          value: 'default',
          addType: 'more',
        }
      ]
    },
    {
      label: '报文分支子节点',
      value: 'case',
      addType: 'more'
    },
  ],
  single: [{
    label: '报文',
    value: 'policy',
    addType: 'more'
  }]
}

// 初始化树的配置信息
var setting = {
  edit: {
    drag: {
      autoExpandTrigger: true,
      prev: true,
      inner: true,
      next: true,
      isCopy: false,
      isMove: true
    },
    enable: true,
    showRemoveBtn: false,
    showRenameBtn: false
  },
  data: {
    key: {
      children: "children",
      name: "label"
    }
  },
  callback: {
    onClick: addConfigModel,
    onRightClick: OnPktRightClick,
    beforeDrag: beforeDrag
  }
};

var rule = {
  transCode: {
    required: true
  }
};

var message = {
  transCode: {
    required: "请输交易码"
  }
};


$(function () {
  getInsystem()
  getOutsystem()

  if (oper === 'edit' || oper === 'view') {
    getDetail()
  }
  $.common.initFormInfo();




    var commType = getQueryString('commType')

    /**初始化的时候选择 接入接出类型
     *
     * 判断依据，如果groupCode 为空  那么就为 接出
     * pkt_range_select
     **/
    if (oper === 'edit') {
      if (commType == 1) { // 接出
        $("#pkt_range_select").val(1);
        $("#pkt_groupCode_select").empty();
        $("#yfe_select_div").hide();
        $("#yfe_select_div").find("#pktList_querybtn_div").remove();
        $("#querybtndiv").remove();
        $("#thirdsys_div").show();
        $("#thirdsys_div").append(createQueryButton());
      } else if (commType == 0){ // 接入
        $("#pkt_range_select").val(0);
        $("#thirdsys_div").hide();
        $("#thirdsys_div").find("#pktList_querybtn_div").remove();
        $("#yfe_select_div").show();
        $("#yfe_select_div").append(createQueryButton());
      }
    }else{ //新增
      $("#thirdsys_div").hide();
      $("#yfe_select_div").show();
      $("#yfe_select_div").append(createQueryButton());
    }


  bindEvents();

  //初始化复制选项页面信息
  if ("pktEdit" != menuCopyType) {
    menuCopyType = "pktEdit";
    menuCopyNodes = null;
  }

  $("#pkt_node_configForm").validate({
    rules: {
      type: {
        required: true
      },
      encoding: {
        required: true
      },
      name: {
        required: true,
      },
      xpath: {
        required: true,
      },
      len: {
        required: true,
      },
      delimChar: {
        required: true,
      },
      len_cnpas12: {
        required: true,
      },
      tag: {
        required: true,
      },
      iso8583tag:{
        required: true,
        // checkPositiveNumberL128: true
      },
      prefix: {
        required: true,
      },
      suffix: {
        required: true,
      },
      count : {
        required: true,
      },
      condition : {
        required: true,
      }
    },
    messages: {
      type: {
        required: "请选择报文类型"
      },
      encoding: {
        required: "请选择编码方式"
      },
      name: {
        required: "请输入名称"
      },
      len:{
        required: "请输入字段长度"
      },
      delimChar:{
        required: "请输入分隔符字符"
      },
      xpath:{
        required: "请输入path"
      },
     /* tag:{
        required: "请输入tag值"
      },*/
      len_cnpas12:{
        required: "请输入长度"
      },
      iso8583tag:{
        required: "请输入字段序号"
      },
      prefix:{
        required: "请输入报文域前缀"
      },
      suffix:{
        required: "请输入报文域后缀"
      },
      condition: {
        required: "请输入分支条件"
      }
    },
    focusCleanup: true
  });


});


function getDetail(id) {
  var data = {
    commType: getQueryString('commType'),
    systemCode: getQueryString('systemCode'),
    groupCode: getQueryString('groupCode'),
    transCode: getQueryString('transCode')
  }
  $('#pkt_transCode_txt').val(data.transCode)
  if (data.commType == 0) getGroup(data.systemCode)
  createAjax(data)

}



//获取接入项目列表
function getInsystem() {
  $.operate.get(api + '/comm/insystem/insys_list', function (res) {
    res.data.forEach(function (item) {
      if (getQueryString('systemCode') && getQueryString('systemCode') == item.code) {
        $("#pkt_systemCode_select").append("<option selected='selected' value=" + item.code + ">" + item.name + "</option>");
      } else {
        $('#pkt_systemCode_select').append('<option value="' + item.code + '">' + item.name + '</option>')
      }

    })
  }, false)
}

//获取接出项目列表
function getOutsystem() {
  $.operate.get(api + '/comm/outsystem/outsys_list', function (res) {
    res.data.forEach(function (item) {
      if (getQueryString('systemCode') && getQueryString('systemCode') == item.code) {
        $("#pkt_thirdsys_select").append("<option selected='selected' value=" + item.code + ">" + item.name + "</option>");
      } else {
        $('#pkt_thirdsys_select').append('<option value="' + item.code + '">' + item.name + '</option>')
      }
    })
  }, false)
}

//根据接入项目名称获取服务列表
function getGroup(code) {
  $('#groupCode_select').find('option').remove()
  $('#groupCode_select').append('<option value=""></option>')
  $.operate.get(api + '/comm/group/group_list/code/' + code, function (res) {
    res.data.forEach(function (item) {
      if (getQueryString('groupCode') && getQueryString('groupCode') == item.code) {
        $("#pkt_groupCode_select").append("<option selected='selected' value=" + item.code + ">" + item.name + "</option>");
      } else {
        $('#pkt_groupCode_select').append('<option value="' + item.code + '">' + item.name + '</option>')
      }
    })
  }, false)
}


// 添加查询按钮
function createQueryButton() {
  return '<div id="pktList_querybtn_div" class="col-sm-2" style="text-align:right;padding-right:20px;">'
    + '<button type="button" onclick="queryPktListFunc()" class="btn btn-primary fa fa-search">查询</button>'
    + '</div>';
}





//查询树
function queryPktListFunc() {
  if ($("#pktConditionForm").valid()) {
    $("#pktnode_div").empty()
    var data = {}
    var commType = $("#pkt_range_select").val()
    data.commType = commType
    data.transCode = $("#pkt_transCode_txt").val()
    if (commType == 0) {
      data.systemCode = $("#pkt_systemCode_select").val();
      data.groupCode = $("#pkt_groupCode_select").val();
    } else {
      data.systemCode = $("#pkt_thirdsys_select").val();
      data.groupCode = ''
    }

    createAjax(data)


  }

}

function createAjax(data) {
  $.ajax({
    url: queryPktListTreeUrl,
    type: "POST",
    contentType: 'application/json;charset=utf-8', // 设置请求头信息
    dataType: "json",
    data: JSON.stringify(data), // 将Json对象序列化成Json字符串，JSON.stringify()原生态方法
    // data: $.toJSON(node),
    // //将Json对象序列化成Json字符串，toJSON()需要引用jquery.json.min.js
    success: function (res) {
      var treeData = []
      var sysName = $("#pkt_systemCode_select").find("option:selected").text()
      if (res.data == null || res.data.content == null) {
        // this.searchData.pktId = null
        var configName = data.groupCode ?
          data.systemCode + "." + data.groupCode + "." + data.transCode + ".报文配置" :
          data.systemCode + "." + data.transCode + ".报文配置"
        treeData = [{
          "id": 0,
          "label": configName,
          "children": [{
            "id": 1,
            "label": "组包",
            "children": [],
            "dropInner": true, //新增节点是兄弟节点还是子节点
            "pktType": "pack",
            "addType": 'single', //新增的节点有哪些内容
            "rootType": 'pack', //新增的节点有哪些内容
            "noDrag": true
          }, {
            "id": 2,
            "label": "解包",
            "children": [],
            "dropInner": true,
            "pktType": "unpack",
            "addType": 'single',
            "rootType": 'unpack', //新增的节点有哪些内容
            "noDrag": true
          }],
          "dropInner": true,
          "root": true,
          "pktType": null
        }]

      } else {
        pktId = res.data.pktId
        treeData = res.data.content
      }

      $.fn.zTree.init($("#pktList_treeview"), setting, treeData);
      zTree = $.fn.zTree.getZTreeObj("pktList_treeview");
      rMenu = $("#rMenu");
    }
  });
}

/**
 * 创建请求参数
 */
function createRequestParam(node) {
  var range = $("#pkt_range_select").val();
  var systemCode;
  var groupCode;
  if (range == "0") {
    systemCode = $("#pkt_systemCode_select").val();
    groupCode = $("#pkt_groupCode_select").val();
  } else if (range == "1") {
    groupCode = '';
    systemCode = $("#pkt_thirdsys_select").val();
  }
  var transCode = $("#pkt_transCode_txt").val();
  return {
    "commType": range,
    "systemCode": systemCode,
    "groupCode": groupCode,
    "transCode": transCode,
    "data": node
  }
}


function bindEvents() {
  $("#pkt_systemCode_select").bind('change', function () {
    $("#pkt_groupCode_select").empty();
    var sysId = $("#pkt_systemCode_select").val()
    getGroup(sysId)
  });

  $("#pkt_groupCode_select").bind('change', function () {
    queryPktListFunc();
  });

  $("#pkt_thirdsys_select").bind('change', function () {
    queryPktListFunc();
  });

  //保存报文配置
  $("#savePktTree").bind("click", function () {
    if ($("#pktList_treeview").html().trim() == "") {
      $.modal.msgError("保存失败，请正确加载界面信息！");
      return;
    }
    var parent = window.parent;
    try {
      var node = zTree.getNodeByTId("treeview_1");
      var requestParam = createRequestParam(node);
      if (pktId) requestParam.pktId = pktId
      $.ajax({
        url: saveCfg,
        type: pktId ? "PUT" : "POST",
        contentType: 'application/json;charset=utf-8', // 设置请求头信息
        dataType: "json",
        data: JSON.stringify(requestParam), // 将Json对象序列化成Json字符串，JSON.stringify()原生态方法
        // data: $.toJSON(node),
        // //将Json对象序列化成Json字符串，toJSON()需要引用jquery.json.min.js
        success: function (result) {
          if (result.data) {
            $.modal.close()
            parent.$.modal.msgSuccess('保存成功');
            parent.$.table.refresh();
          } else {
            $.modal.msgError("保存失败！");
          }
        }
      });
    } catch (e) {
      console.log(e);
      $.modal.msgError("保存失败！");
    }
  });

  $("#pkt_range_select").bind("change", function () {
    var commType = $(this).val();
    if (commType == 1) { // 接出
      $("#pkt_range_select").val(1);
      $("#pkt_groupCode_select").empty();
      $("#yfe_select_div").hide();
      $("#yfe_select_div").find("#pktList_querybtn_div").remove();
      $("#querybtndiv").remove();
      $("#thirdsys_div").show();
      $("#thirdsys_div").append(createQueryButton());
    } else if (commType == 0){ // 接入
      $("#pkt_range_select").val(0);
      $("#thirdsys_div").hide();
      $("#thirdsys_div").find("#pktList_querybtn_div").remove();
      $("#yfe_select_div").show();
      $("#yfe_select_div").append(createQueryButton());
    }
  });
}


function filter(node) {
  return (node.type != null);
}

function error(d) {
  $.modal.msgError(d.message);
}

function addRootTreeNode(type, addType) {
  hideRMenu();
  var name;
  if (type == "policy") {
    name = "报文";
  } else if (type == "field") {
    name = "报文字段";
  } else if (type == "loop") {
    name = "报文循环";
  } else if (type == "struct") {
    name = "报文域";
  } else if (type == "switch") {
    name = "报文分支";
  } else if (type == "case") {
    name = "报文分支子节点";
  }

  var useType = setUseType(pktSelectNode);
  var newNode = {
    title: name,
    label: name,
    type: type,
    dropInner: true,
    dropRoot: false,
    useType: useType,

    rootType: pktSelectNode.rootType == pktSelectNode.pktType ? pktSelectNode.pktType : pktSelectNode.rootType,
    value: type,
    pktType: type,
    addType: addType
  };
  var pNode = zTree.addNodes(pktSelectNode, newNode);
  if (type == "switch") {
    var pId = pNode[0].tId;
    var defaultNode = {
      title: "分支默认条件",
      label: "分支默认条件",
      // type: "default",
      dropInner: true,
      dropRoot: false,
      useType: "default",

      rootType: pktSelectNode.rootType == pktSelectNode.pktType ? pktSelectNode.pktType : pktSelectNode.rootType,
      value: 'default',
      pktType: 'default',
      addType: addType
    };
    if (pktSelectNode.pktType === 'policy') {
      defaultNode.type = (pktSelectNode.dataModel && pktSelectNode.dataModel.type) ? pktSelectNode.dataModel.type : ''
    } else {
      defaultNode.type = pktSelectNode.type ? pktSelectNode.type : ''
    }
    zTree.addNodes(pNode[0], defaultNode);
  }
}

function setUseType(node) {
  // var useType = node.useType;
  var useType = node.pktType;
  if (!useType) {
    useType = node.model.useType;
  }
  return useType;
}

function beforeDrag(treeId, treeNodes) {
  for (var i = 0, l = treeNodes.length; i < l; i++) {
    if (treeNodes[i].drag === false) {
      curDragNodes = null;
      return false;
    } else if (treeNodes[i].parentTId
      && treeNodes[i].getParentNode().childDrag === false) {
      curDragNodes = null;
      return false;
    }
  }
  curDragNodes = treeNodes;
  return true;
}

/**
 * 单击节点添加属性
 */
function addConfigModel(event, treeId, treeNode, clickFlag) {
  pktSelectNode = treeNode;
  nodeTid = treeNode.tId;
  $("#pktnode_div").empty()
  if (typeConfig[treeNode.pktType]) {
    $("#pktnode_div").load(typeConfig[treeNode.pktType].url);

  }


}

//点击新增节点
function addNodeSelect() {
  $('#dropdown-menu').show()
}
// 删除节点
function removeTreeNode() {
  hideRMenu();
  var nodes = zTree.getSelectedNodes();
  if (pktSelectNode.children && pktSelectNode.children.length > 0) {
    $.modal.confirm('要删除的节点是父节点，如果删除将连同子节点一起删掉。是否确认删除该节点？', function () {
      zTree.removeNode(pktSelectNode);
    })

  } else {
    $.modal.confirm('是否确认删除该节点？', function () {
      zTree.removeNode(pktSelectNode);
    })
  }
}
// 复制节点
function copyTreeNode() {
  // menuCopyNodes = zTree.getSelectedNodes();
  menuCopyNodes = pktSelectNode
  hideRMenu();
  $("#pktnode_div").empty();
}

//粘贴节点
function postTreeNode() {
  if (null != menuCopyNodes) {
    zTree.addNodes(pktSelectNode, menuCopyNodes);
    menuCopyNodes = null;
  } else {
    $.modal.msgError("请选择需要复制的节点！");
  }
  hideRMenu();
}
//剪切节点
function cutTreeNode() {
  // menuCopyNodes = zTree.getSelectedNodes();
  // zTree.removeNode(menuCopyNodes[0]);
  menuCopyNodes = pktSelectNode;
  zTree.removeNode(menuCopyNodes);
  hideRMenu();
  $("#pktnode_div").empty();
}

// 右键菜单加载
function OnPktRightClick(event, treeId, treeNode) {
  if (treeNode.root) return
  $('#dropdown-menu').empty()
  pktSelectNode = treeNode
  var menuList = addList[treeNode.addType]
  menuList.forEach(function (item) {
    $('#dropdown-menu').append('<li onclick="addRootTreeNode(\'' + item.value + '\',\'' + item.addType + '\')"><a tabindex="-1">' + item.label + '</a></li>')
  })
  $("#dropdown-menu").css({
    "position": "absolute",
    "top": "-2px",
    "left": "100%",
    "height": "100%",
    "overflow": 'auto',
    'display': 'none'
  });

  $("#rMenu #dropdown-menu-parent").show();
  var y = event.clientY
  var x = event.clientX
  y += $(window).scrollTop() ;
  x += document.body.scrollLeft;
  rMenu.css({
    "top": y + "px",
    "left": x + "px",
    "visibility": "visible"
  });

  $("body").bind("mousedown", onBodyMouseDown);


}

function onBodyMouseDown(event) {
  if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
    rMenu.css({
      "visibility": "hidden"
    });
  }
}


function hideRMenu() {
  if (rMenu)
    rMenu.css({
      "visibility": "hidden"
    });
  $("body").unbind("mousedown", onBodyMouseDown);
}

/**
 * 保存节点配置
 */
function saveNodeInfo() {
  var divIsEmpty = $("#pktnode_div").html().trim();
  if ("" == divIsEmpty || divIsEmpty.length == 0) {
    return;
  }
  if ($("#pkt_node_configForm").valid()) {
    //保存前做额外的定制化判断 tag 长度必须大于2且最后一字符必须为字母
    var policyVal = $("#policyType_select").val();
    if (undefined == policyVal) {
      if ("disabled" != $("#cnpas12_field_len_txt").attr("disabled")) {
        var len_text = $("#cnpas12_field_len_txt").val();
        if (undefined != len_text) {
          if (0 != len_text.length) {
            var reg = /^[0-9]+([a-z]|[A-Z])+$/;
            if (!reg.test(len_text)) {
              $.modal.msgError("长度必须大于2且最后一字符必须为字母！");
              return;
            }
          }
        }
      }
    }

    var data = $('#pkt_node_configForm').serializeObject()
    data.pktType = pktSelectNode.pktType
    var nodeLabel
    if (data.pktType === 'policy') {
      nodeLabel = typeConfig[pktSelectNode.pktType].type[data.type] + "：" + data.desc
    } else {
      var desc = data.name ? data.name + ' - ' + data.desc : data.desc
      nodeLabel = typeConfig[pktSelectNode.pktType].label + "：" + desc
    }

    pktSelectNode.label = nodeLabel;
    pktSelectNode.dataModel = data;
    pktSelectNode.formData = data;
    zTree.refresh();
    $.modal.msgSuccess('保存成功！')


  }

}

//子节点获取报文类型，勿删！！！！！！！！！！！其他页面有用到此方法
function getPolicyType(data){
  var targetNode = data.getParentNode()
  if (targetNode.pktType === 'policy'){
    return targetNode.dataModel ? targetNode.dataModel.type : ''
  }else{
    return getPolicyType(targetNode)
  }
}